<?php
class CrontabController extends Zend_Controller_Action
{
	public function init()
	{
		set_time_limit(99999);
		ini_set('display_errors', 1);
		ini_set('memory_limit', '-1');
	}
	
	public function indexAction()
	{
		exit;
	}
	
	#Actual Stock Level
	public function actualValueAction()
	{
		$objConfig	= new CConfig();
		$arrCountry	= $objConfig->country_list();
		
		if($arrCountry)
		{
			foreach($arrCountry as $country)
			{
				$obj		= new QBForecast($country['id']);
				if( !CCommon::exists_table($obj->_table) )
				{
					echo '<br />'.$obj->_table;
					continue;
				}
				
				$arrData	= $obj->get_all();
				if($arrData)
				{
					self::update_WMS($arrData, $country['id']);
					echo '<h1>Done ['.$country['id'].']</h1>';
				}
			}
		}
		exit;
	}
	
	static function update_WMS($p_arrData, $p_strCountryId)
	{
		$intConfig	= 500;
		$arrSku		= array();
		$db			= Zend_Registry::get('db');
		foreach($p_arrData as $data)
		{
			if( !in_array($data['sku'], $arrSku) ){
				$arrSku[]	= $data['sku'];
			}
			
			if(count($arrSku)==$intConfig)
			{
				$arrStock	= CCommon::get_info_sku(implode(',', $arrSku), $p_strCountryId);
				if($arrStock)
				{
					$strQuery	= 'UPDATE '.$p_strCountryId.'_forecasts SET asl=(CASE sku';
					$strQuery1	= ', in_transit=(CASE sku';
					foreach($arrStock as $sku=>$item)
					{
						$actual_sl			= intval($item['For Sale']);
						$pending_inbound	= intval($item['In Transit']);
						$strQuery			= $strQuery. ' WHEN "'.$sku.'" THEN '.$actual_sl;
						$strQuery1			= $strQuery1. ' WHEN "'.$sku.'" THEN '.$pending_inbound;
					}
					$strQuery	= $strQuery.' END) ';
					$strQuery	= $strQuery. $strQuery1.' END), exponential_smoothening=tsl-asl-in_transit, reorder=IF(asl+in_transit<msl, "Yes", "No") WHERE sku IN ("'.implode('","', $arrSku).'")';
					$arrSku		= array();
					
					$db->execute($strQuery);
				}
			}
		}
		
		if($arrSku)
		{
			$arrStock	= CCommon::get_info_sku(implode(',', $arrSku), $p_strCountryId);
			if($arrStock)
			{
				$strQuery	= 'UPDATE '.$p_strCountryId.'_forecasts SET asl=(CASE sku';
				$strQuery1	= ', in_transit=(CASE sku';
				foreach($arrStock as $sku=>$item)
				{
					$actual_sl			= intval($item['For Sale']);
					$pending_inbound	= intval($item['In Transit']);
					$strQuery			= $strQuery. ' WHEN "'.$sku.'" THEN '.$actual_sl;
					$strQuery1			= $strQuery1. ' WHEN "'.$sku.'" THEN '.$pending_inbound;
				}
				$strQuery	= $strQuery.' END) ';
				$strQuery	= $strQuery. $strQuery1.' END), exponential_smoothening=tsl-asl-in_transit, reorder=IF(asl+in_transit<msl, "Yes", "No") WHERE sku IN ("'.implode('","', $arrSku).'")';
				$arrSku		= array();
				$db->execute($strQuery);
			}
		}
		$db->closeConnection();
	}
	#Actual Stock Level
	
	#Sending Feature
	public function emailAction()
	{
		$arrAdmin	= QAdminUser::search(null, 1, null);
		
		if($arrAdmin)
		{
			$arrCountry	= CConfig::country_list();
			if($arrCountry)
			{
				foreach($arrCountry as $country)
				{
					$arrAdminUser	= array();
					foreach($arrAdmin as $data)
					{
						if($data['country']==$country['id'] && $data['email'] && !in_array(trim($data['email']), $arrAdminUser) ){
							$arrAdminUser[]	= trim($data['email']);
						}
					}
			
					if($arrAdminUser)
					{
						$arrParams	= array('reorder'=>'yes');
						$obj		= new QBForecast($country['id']);
						$arrResult	= $obj->get(null, 'all', null, $arrParams);
						
						if($arrResult)
						{
							$filename	= $this->_createExtract($arrResult, $country['id']);
							$this->view->filename	= $filename;
							/*
							$arrTitle	= array();
							foreach($arrResult as $result)
							{
								foreach($result as $title=>$value){
									$arrTitle[]	= ucfirst(trim(str_replace('_', ' ', $title)));
								}
								break;
							}
							
							$this->view->arrTitle	= $arrTitle;
							$this->view->arrResult	= $arrResult;
							*/
							
							$strBody	= $this->view->fetch('crontab/email.tpl');
							$strSubject	= 'Report from dragontool ['.date('Y-m-d').']';
							foreach($arrAdminUser as $email)
							{
								#$email	= 'xitrumhaman@yahoo.com';
								CCommon::send_mail($strSubject, $strBody, $email);
							}
						}	
					}
				}
			}
		}
		exit;
	}
	
	private function _createExtract($p_arrResult, $p_strCountry)
	{
		$path		= ROOT_SITE.'/data/email';
		@mkdir($path);
		$filename	= $p_strCountry.'.'.date('YmdHis').'.csv';
		$path		= $path.'/'.$filename;
		$handle		= fopen($path, 'w+');
		
		$arrTitle	= array();
		foreach($p_arrResult as $result)
		{
			foreach($result as $title=>$value){
				$arrTitle[]	= ucfirst(trim(str_replace('_', ' ', $title)));
			}
			break;
		}
		fputcsv($handle, $arrTitle);
		foreach($p_arrResult as $data)
		{
			$arrRecord		= array();
			foreach($data as $value){
				$arrRecord[]	= $value;
			}
			fputcsv($handle, $arrRecord);
		}
		fclose($handle);
		
		return $filename;
	}
	#Sending Feature
	
	private function _createExtractNoHeader($p_arrResult, $p_strCountry)
	{
		$path		= ROOT_SITE.'/data/email';
		@mkdir($path);
		$filename	= $p_strCountry.'.'.date('YmdHis').'.csv';
		$path		= $path.'/'.$filename;
		$handle		= fopen($path, 'w+');
		
		foreach($p_arrResult as $data)
		{
			$arrRecord		= array();
			foreach($data as $value){
				$arrRecord[]	= str_replace( "_", " ", $value);
			}
			fputcsv($handle, $arrRecord);
		}
		fclose($handle);
		
		return $filename;
	}
	
	#Supplier Data
	public function supplierDataAction()
	{
		$objConfig	= new CConfig();
		$arrCountry	= $objConfig->country_list();
		if($arrCountry)
		{
			foreach($arrCountry as $country)
			{
				self::_dataSupplier($country['id']);
			}
		}
		exit;
	}
	
	static function _dataSupplier($p_strCountry)
	{
		if( $p_strCountry=='vi' ){
			return;
		}
		$objArchive	= new QArchive($p_strCountry);
		$objSupplier= new QSupplier($p_strCountry);
		if( !CCommon::exists_table($objArchive->_table) )
		{
			echo '<br />'.$objArchive->_table.' is not exists.';
			continue;
		}
		if( !CCommon::exists_table($objSupplier->_table) )
		{
			echo '<br />'.$objSupplier->_table.' is not exists.';
			continue;
		}
		
		$arrData			= $objArchive->get_all();
		if($arrData)
		{
			$arrSku			= array();
			$arrDataSupplier= array();
			$index			= 0;
			foreach($arrData as $data)
			{
				if( !in_array( $data['sku'], $arrSku) ){
					$arrSku[]	= $data['sku'];
					$index++;
				}
				if($index==500)
				{
					$arrTemp			= $objSupplier->get_oms(implode('","', $arrSku), false);
					$arrDataSupplier	= $arrDataSupplier ? array_merge($arrDataSupplier, $arrTemp) : $arrTemp;
					$arrSku				= array();
					$index				= 0;
				}
			}
			
			if($arrSku)
			{
				$arrTemp	= $objSupplier->get_oms(implode('","', $arrSku));
				$arrDataSupplier	= $arrDataSupplier ? array_merge($arrDataSupplier, $arrTemp) : $arrTemp;
			}
			
			if($arrDataSupplier)
			{
				return;
				$db			= Zend_Registry::get('db');
				$strQuery	= '
					TRUNCATE '.$objSupplier->_table.';
					INSERT INTO '.$objSupplier->_table.'(sku, supplier) VALUES
				';
				$index		= 0;
				foreach($arrDataSupplier as $data)
				{
					if($index>0){
						$strQuery	= $strQuery.', ';
					}
					$strQuery	= $strQuery.'("'.trim($data['sku']).'", "'.trim($data['supplier']).'")';
					$index++;
					
					if($index==300)
					{
						$db->execute($strQuery, false);
						$strQuery	= '
							INSERT INTO '.$objSupplier->_table.'(sku, supplier) VALUES
						';
						$index	= 0;
					}
				}
				if($index>0){
					$db->execute($strQuery);
				}
				
				$db->closeConnection();
			}
		}
	}
	#Supplier Data
  
  public function wmsqueryAction()
  {
	//	$this->connectSSH();
		$arrAdmin	= QAdminUser::search(null, 1, null);
		
		$strSubject ="WM Query";
		$email ="anil-kumar.singh@lazada.com";

		if($arrAdmin)
		{
			$arrCountry	= CConfig::country_list();
			if($arrCountry)
			{
				foreach($arrCountry as $country)
				{
					if($country['id'] =='ph' || $country['id'] =='th' || $country['id'] =='ma')	
					{						
						$arrParams	= array('reorder'=>'yes');
						$obj		= new QWms($country['id']);
						$arrResult	= $obj->CrontabWMSQuery();
						
					/*	$now = getdate();
						$today = date('Y-m-d H:i:s', mktime($now['hours'], $now['minutes'], $now["seconds"], $now['mon'], $now['mday'], $now['year']));
							
						$strBody ="";
							
						if($arrResult)
						{
							$strBody ="<h1> WMS Query Data Date: " .$today . "</h1><table border='1px'><thead>";
								
							foreach (array_keys($arrResult[0]) as $key)
							{
								$strBody .="<th>" . $key . "</th>";
							}
								
							$strBody .="</thead><tbody>";
							$i =0;	
							foreach ($arrResult as $item)
							{
								$i +=1;	
								$strBody .="<tr>";
								foreach (array_keys($arrResult[0]) as $key)
								{
									$strBody .= "<td>" . $item[$key] ."</td>";
								}
								$strBody .="</tr>";
							}
						}	
						$strBody .= "</tbody></table>";
						
						CCommon::send_mail($strSubject, $strBody, $email); */
						
						$filename	= $this->_createExtract($arrResult, $country['id']);
						$this->view->filename	= $filename;
						
						$strBody	= $this->view->fetch('crontab/email.tpl');
						$strSubject	= 'WMS Query dragontool ['.date('Y-m-d').']';
						
						CCommon::send_mail($strSubject, $strBody, $email);
					
					}
				}
				echo "Send Email Successful !";
			}
		}
		exit;
	}
	
	public function dailyreportAction()
	{
		
	}
	
	public function queryExecuteAction()
	{
		$arrAdmin	= QAdminUser::search(null, 1, null);
		$now = getdate();	
		$this->view->today = date('d-M-y H:i:s', mktime($now['hours'], $now['minutes'], $now["seconds"], $now['mon'], $now['mday'], $now['year']));
		
		$this->view->dayFilename =  date('dmY', mktime($now['hours'], $now['minutes'], $now["seconds"], $now['mon'], $now['mday'], $now['year']));
		
		$strSubject ="";
		//$email ="phanvantiep@gmail.com";
		$email ="anil-kumar.singh@lazada.com";
		$arrCountry	= CConfig::country_list();
		
		if($arrAdmin)
		{
			foreach($arrCountry as $country)
			{		
				if($country['id'] =='th') 	
				{						
					$arrParams	= array('reorder'=>'yes');
					$obj		= new QWms($country['id']);
					$arrResult	= $obj->dailyReport($country['name'], $country['id']);
					$this->view->arrDataTh = $arrResult["maindata"];
					
					$this->writeOrder($arrResult["orderdata"], $this->view->today, $country['name']);
				}
			
				if($country['id'] =='ma') 	
				{						
					$arrParams	= array('reorder'=>'yes');
					$obj		= new QWms($country['id']);
					$arrResult	= $obj->dailyReport($country['name'], $country['id']);
					$this->view->arrDataMa = $arrResult["maindata"];
					
					$this->writeOrder($arrResult["orderdata"], $this->view->today, $country['name']);
				}
				
				if($country['id'] =='ph') 	
				{						
					$arrParams	= array('reorder'=>'yes');
					$obj		= new QWms($country['id']);
					$arrResult	= $obj->dailyReport($country['name'], $country['id']);
					$this->view->arrDataPh = $arrResult["maindata"];
					
					$this->writeOrder($arrResult["orderdata"], $this->view->today, $country['name']);
				} 
				
				if($country['id'] =='id') 	
				{						
					$arrParams	= array('reorder'=>'yes');
					$obj		= new QWms($country['id']);
					$arrResult	= $obj->dailyReport($country['name'], $country['id']);
					$this->view->arrDataId = $arrResult["maindata"];
					
					$this->writeOrder($arrResult["orderdata"], $this->view->today, $country['name']);
				} 
			}	
			
		
			$strBody	= $this->view->fetch('crontab/dailyreport.tpl');
			$strSubject	= 'Daily Report ['.date('Y-m-d').']';
			
			CCommon::send_mail($strSubject, $strBody, $email);
			CCommon::send_mail($strSubject, $strBody, "phanvantiep@gmail.com");
			//CCommon::send_mail($strSubject, $strBody, "pierre.poignant@lazada.com");
			
			$objDailyReport = new CDailyReport();
			$flag =  $objDailyReport->save($strBody);
			echo "Send Email Successful !";
		}
		exit;
	}
	
	private function writeOrder($arrOrder, $date, $countryName)
	{
		$objDailyReport = new CDailyReport();	
										
		foreach($arrOrder as $key=>$value)
		{
			$this->view->arrData = $arrOrder[$key];
			$this->view->countryName = $countryName;
			$this->view->date = $date;
			
			$strBody	= $this->view->fetch('dailyreport/view.order.generate.tpl');			
			$objDailyReport->saveViewOrder($strBody, $key, 'item');
		}
	}
	
	public function updateImageurlAction()
	{
		$now = getdate();	
		$today = date('d-M-y H:i:s', mktime($now['hours'], $now['minutes'], $now["seconds"], $now['mon'], $now['mday'], $now['year']));
		echo 'Start date : ' . $today . '<br />';
		
		$arrCountry	= CConfig::country_list();
		foreach($arrCountry as $country)
		{		
			if($country['id'] =='vi') 	
			{						
				$objProductImage = new QProductImage('vi');
				$objProductImage->getImageUrl();
				echo $country['name'] . ' success' . '<br />';
			}
					
			if($country['id'] =='th') 	
			{						
				$objProductImage = new QProductImage('th');
				$objProductImage->getImageUrl();
				echo $country['name'] . ' success' . '<br />';
			}
			
			if($country['id'] =='ma') 	
			{						
				$objProductImage = new QProductImage('ma');
				$objProductImage->getImageUrl();
				echo $country['name'] . ' success' . '<br />';
			}
				
			if($country['id'] =='ph') 	
			{						
				$objProductImage = new QProductImage('ph');
				$objProductImage->getImageUrl();
				echo $country['name'] . ' success' . '<br />';
			} 
				
			if($country['id'] =='id') 	
			{						
					$objProductImage = new QProductImage('id');
					$objProductImage->getImageUrl();
				echo $country['name'] . ' success' . '<br />';
			} 
		}	
		
		$now = getdate();	
		$today = date('d-M-y H:i:s', mktime($now['hours'], $now['minutes'], $now["seconds"], $now['mon'], $now['mday'], $now['year']));
		echo 'End date : ' . $today . '<br />';
		
		echo 'Sucecss all 5 country';
		exit;
	}
	
	public function getSupplierAction()
	{
		$now = getdate();	
		$today = date('d-M-y H:i:s', mktime($now['hours'], $now['minutes'], $now["seconds"], $now['mon'], $now['mday'], $now['year']));
		
		echo 'Start date : ' . $today;
		
		$arrCountry	= CConfig::country_list();
		foreach($arrCountry as $country)
		{			
			$objSupplier = new QSupplier($country['id']);
			$arrResult = $objSupplier->getSupplierInfor();
				
			if($arrResult['sendEmailNew'] || ($arrResult['sendEmailRemove']) /* && $country['id'] =='th' */)
			{
				$arrEmail = CAdminUser::getbyGroup(ADMINISTRATOR , $country['id']);
				
				
				$this->view->countData = count($arrResult['sendEmailNew']);
				$this->view->today =	$today;
				$this->view->arrData = $arrResult['sendEmailNew'];
				
				$this->view->arrDataRemove = $arrResult['sendEmailRemove'];
				
				$strBody = $this->view->fetch('crontab/getsupplier.tpl'); 
				
				foreach ($arrEmail as $email)
				{
					if( isset($email['email']) && $email['email']);
					{
						CCommon::send_mail("Get new suppliers", $strBody, $email['email']);
					}
				}
			}
			
		 echo $country['name'] . ' success' . '<br />';
		}	
		
		$now = getdate();	
		$today = date('d-M-y H:i:s', mktime($now['hours'], $now['minutes'], $now["seconds"], $now['mon'], $now['mday'], $now['year']));
		echo 'End date : ' . $today . '<br />';
		
		echo ' <br /> Sucecss all 5 country';
		exit;
	}
	
	public function getSalesdataAction()
	{
		ini_set('memory_limit', '-1');			
		$country			= $this->_request->getParam('country', null);
		$now = getdate();	
		$today = date('d-M-y H:i:s', mktime($now['hours'], $now['minutes'], $now["seconds"], $now['mon'], $now['mday'], $now['year']));
		echo 'Start date : ' . $today . '<br />';

		$objSales = new QSale($country);
		
		try
		{
			$objSales->getSaleDataFromOMS();
			echo $country . ' success get data' . '<br />';	
			$arr_Params = array(
				'name' => 'getSaleDataFromOMS',
				'description' => 'getSaleDataFromOMS success',
				'status' => 'success',
				'country' => $country,
				'created_at' => new Zend_Db_Expr('NOW()')
				);
			QLogSystem::insert($arr_Params);
				
			$now = getdate();	
			$today = date('d-M-y H:i:s', mktime($now['hours'], $now['minutes'], $now["seconds"], $now['mon'], $now['mday'], $now['year']));
			echo 'End date : ' . $today . '<br />';
		}
		catch (Exception $e)  
		{
			$arr_Params = array(
				'name' => 'getSaleDataFromOMS',
				'description' => $e,
				'status' => 'fail',
				'country' => $country,
				'created_at' =>  new Zend_Db_Expr('NOW()')
				);
			QLogSystem::insert($arr_Params );
				
			throw new Exception($e);
		}		
		exit;
	}
	
	public function generateAutoAction()
	{
		ini_set('memory_limit', '-1');			
		$country			= $this->_request->getParam('country', null);
		$now = getdate();	
		$today = date('d-M-y H:i:s', mktime($now['hours'], $now['minutes'], $now["seconds"], $now['mon'], $now['mday'], $now['year']));
		echo 'Start date : ' . $today . '<br />';
		
		$objCGenerate = new CGenerate($country);	
		try
		{			
			$objCGenerate->generateAuto("callback", -1);
			
			$this->genereateSendEmail($country);
			
			echo $country . ' success generate data' . '<br />';
			
			$arr_Params = array(
				'name' => 'Generate forecats',
				'description' => 'Generate forecats success',
				'status' => 'success',
				'country' => $country,
				'created_at' => new Zend_Db_Expr('NOW()')
				);
			QLogSystem::insert($arr_Params);
			
			$now = getdate();	
			$today = date('d-M-y H:i:s', mktime($now['hours'], $now['minutes'], $now["seconds"], $now['mon'], $now['mday'], $now['year']));
			echo 'End date : ' . $today . '<br />';
		}
		catch (Exception $e)  
		{
			$arr_Params = array(
				'name' => 'Generate forecats',
				'description' => $e,
				'status' => 'fail',
				'country' => $country,
				'created_at' =>  new Zend_Db_Expr('NOW()')
				);
			QLogSystem::insert($arr_Params);
			
			throw new Exception($e);
		}		
		exit;
		
	}
	
	#Generate
	#Send Email to Buying And Marketing	
	public function genereateSendEmail($country)	
	{
		$arrMakerting	= QAdminUser::search($country, 4, null); //get marketing user
		$arrBuying		= QAdminUser::search($country, 2, null); //get buying user
		$result = array_merge($arrMakerting, $arrBuying);
		
		$adminEmail ="";	
		$arrAdminUser  = QAdminUser::search($country, 1, null); //get Admin user
		if($arrAdminUser)
		{
			$adminEmail = $arrAdminUser[0]['email'];
		}
		$this->view->adminEmail= $adminEmail;
		
		$now = getdate();
		$today = date('Y-m-d H:i:s', mktime($now['hours'], $now['minutes'], $now["seconds"], $now['mon'], $now['mday'], $now['year']));
		$this->view->timeStamp = $today;
		
		if($result)
		{
			$strSubject	= 'Dragon Tool has generated a new forecast ['.$today.']';
			foreach($result as $user)
			{	
				$this->view->userName = $user['admin_username'];
				$strBody	= $this->view->fetch('generate/email.tpl');		
				//$email	= 'phanvantiep@gmail.com';
				$email = $user['email'];
				CCommon::send_mail($strSubject, $strBody, $email);
			}
		}
	}
	
	public function getMsldataAction()
	{
		ini_set('memory_limit', '-1');			
		$country			= $this->_request->getParam('country', null);
		$now = getdate();	
		$today = date('d-M-y H:i:s', mktime($now['hours'], $now['minutes'], $now["seconds"], $now['mon'], $now['mday'], $now['year']));
		echo 'Start date : ' . $today . '<br />';
		
		$objMSL = new QMSLData($country);	
		try
		{			
			$objMSL->getMSLDataFromGenerateForecasts();
			echo $country . ' success get msl data' . '<br />';
				
			$arr_Params = array(
				'name' => 'Get oos data',
				'description' => 'Get msl data success',
				'status' => 'success',
				'country' => $country,
				'created_at' => new Zend_Db_Expr('NOW()')
				);
			QLogSystem::insert($arr_Params);
			
			$now = getdate();	
			$today = date('d-M-y H:i:s', mktime($now['hours'], $now['minutes'], $now["seconds"], $now['mon'], $now['mday'], $now['year']));
			echo 'End date : ' . $today . '<br />';
		}
		catch (Exception $e)  
		{
			$arr_Params = array(
				'name' => 'get msl data',
				'description' => $e,
				'status' => 'fail',
				'country' => $country,
				'created_at' =>  new Zend_Db_Expr('NOW()')
				);
			QLogSystem::insert($arr_Params);
			
			throw new Exception($e);
		}		
		exit;
	}
	
	public function getOosdataAction()
	{
		ini_set('memory_limit', '-1');			
		$country			= $this->_request->getParam('country', null);
		$now = getdate();	
		$today = date('d-M-y H:i:s', mktime($now['hours'], $now['minutes'], $now["seconds"], $now['mon'], $now['mday'], $now['year']));
		echo 'Start date : ' . $today . '<br />';
		
		$objOOS = new QOOSData($country);
		$objMSL = new QMSLData($country);	
		try
		{			
			$objOOS->getOOSDataNoPagingFromOMS();
			echo $country . ' success get oos data' . '<br />';
			
			$arr_Params = array(
				'name' => 'Get oos data',
				'description' => 'Get oos data success',
				'status' => 'success',
				'country' => $country,
				'created_at' => new Zend_Db_Expr('NOW()')
				);
			QLogSystem::insert($arr_Params);
			
			$now = getdate();	
			$today = date('d-M-y H:i:s', mktime($now['hours'], $now['minutes'], $now["seconds"], $now['mon'], $now['mday'], $now['year']));
			echo 'End date : ' . $today . '<br />';
		}
		catch (Exception $e)  
		{
			$arr_Params = array(
				'name' => 'get oos data',
				'description' => $e,
				'status' => 'fail',
				'country' => $country,
				'created_at' =>  new Zend_Db_Expr('NOW()')
				);
			QLogSystem::insert($arr_Params);
			
			throw new Exception($e);
		}		
		exit;
	}
}
?>
